<template>
  <div class="dashboard-container">
    <h1 class="dashboard-title">琴行数据概览</h1>
    
    <el-row :gutter="20" class="data-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-card-content">
            <div class="data-card-value">{{ statistics.studentCount }}</div>
            <div class="data-card-title">学员总数</div>
          </div>
          <div class="data-card-icon student-icon">
            <el-icon><User /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-card-content">
            <div class="data-card-value">{{ statistics.teacherCount }}</div>
            <div class="data-card-title">教师总数</div>
          </div>
          <div class="data-card-icon teacher-icon">
            <el-icon><UserFilled /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-card-content">
            <div class="data-card-value">{{ statistics.finishedCourseCount}} / {{ statistics.courseCount }}</div>
            <div class="data-card-title">消课数 / 课程总数</div>
          </div>
          <div class="data-card-icon course-icon">
            <el-icon><Calendar /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-card-content">
            <div class="data-card-value">{{ statistics.instrumentCount }}</div>
            <div class="data-card-title">乐器种类</div>
          </div>
          <div class="data-card-icon instrument-icon">
            <el-icon><Headset /></el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <h3>学员来源分布</h3>
          </div>
          <div class="chart-container">
            <pie-chart :chart-data="studentSourceData" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <h3>乐器学习分布</h3>
          </div>
          <div class="chart-container">
            <pie-chart :chart-data="instrumentDistributionData" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <h3>学员状态分布</h3>
          </div>
          <div class="chart-container">
            <pie-chart :chart-data="studentStatusData" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <div class="chart-header-content">
              <h3>学员增长趋势</h3>
              <div class="date-picker-container">
                <el-date-picker
                  v-model="studentGrowthDateRange"
                  type="monthrange"
                  range-separator="至"
                  start-placeholder="开始月份"
                  end-placeholder="结束月份"
                  :shortcuts="dateShortcuts"
                  value-format="YYYY-MM"
                  format="YYYY年MM月"
                  @change="handleStudentGrowthDateRangeChange"
                />
              </div>
            </div>
          </div>
          <div class="chart-container">
            <line-chart :chart-data="studentGrowthTrendData" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <div class="chart-header-content">
              <h3>课程消课趋势</h3>
              <div class="date-picker-container">
                <el-date-picker
                  v-model="dateRange"
                  type="monthrange"
                  range-separator="至"
                  start-placeholder="开始月份"
                  end-placeholder="结束月份"
                  :shortcuts="dateShortcuts"
                  value-format="YYYY-MM"
                  format="YYYY年MM月"
                  @change="handleDateRangeChange"
                />
              </div>
            </div>
          </div>
          <div class="chart-container">
            <line-chart :chart-data="courseSalesTrendData" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { User, UserFilled, Calendar, Headset } from '@element-plus/icons-vue'
import PieChart from '@/components/charts/PieChart.vue'
import LineChart from '@/components/charts/LineChart.vue'
import { SOURCE_OPTIONS, STATUS_OPTIONS } from '@/constants/student'
import { getStatement, getStudentGrowth, getCourseTrend } from "@/api/statement"

// 统计数据
const statistics = ref({
  studentCount: 0,
  teacherCount: 0,
  finishedCourseCount: 0,
  courseCount: 0,
  instrumentCount: 0
})

// 学员来源分布数据
const studentSourceData = ref({
  labels: [],
  datasets: [{
    data: [],
    backgroundColor: [
      '#4e73df',
      '#1cc88a',
      '#36b9cc',
      '#f6c23e',
      '#e74a3b',
      '#858796'
    ]
  }]
})

// 学员状态分布数据
const studentStatusData = ref({
  labels: [],
  datasets: [{
    data: [],
    backgroundColor: [
      '#4e73df',
      '#1cc88a',
      '#36b9cc',
      '#f6c23e',
      '#e74a3b',
      '#858796',
      '#5a5c69',
      '#6f42c1',
      '#fd7e14'
    ]
  }]
})

// 学员增长趋势数据
const studentGrowthTrendData = ref({
  labels: [],
  datasets: [{
    label: '新增学员数',
    data: [],
    borderColor: '#1cc88a',
    backgroundColor: 'rgba(28, 200, 138, 0.05)',
    tension: 0.3,
    fill: true
  }]
})

// 学员增长日期范围选择
const studentGrowthDateRange = ref([])

// 乐器分布数据
const instrumentDistributionData = ref({
  labels: [],
  datasets: [{
    data: [],
    backgroundColor: [
      '#4e73df',
      '#1cc88a',
      '#36b9cc',
      '#f6c23e',
      '#e74a3b',
      '#858796',
      '#5a5c69',
      '#6f42c1'
    ]
  }]
})

// 课程销售趋势数据
const courseSalesTrendData = ref({
  labels: [],
  datasets: [{
    label: '月销课节数',
    data: [],
    borderColor: '#4e73df',
    backgroundColor: 'rgba(78, 115, 223, 0.05)',
    tension: 0.3,
    fill: true
  }]
})

// 日期范围选择
const dateRange = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近3个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 2)
      return [start, end]
    }
  },
  {
    text: '最近6个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 5)
      return [start, end]
    }
  },
  {
    text: '最近12个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 11)
      return [start, end]
    }
  }
]

// 处理日期范围变化
const handleDateRangeChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    fetchCourseSalesData(dateRange.value[0], dateRange.value[1])
  }
}

// 处理学员增长日期范围变化
const handleStudentGrowthDateRangeChange = () => {
  if (studentGrowthDateRange.value && studentGrowthDateRange.value.length === 2) {
    fetchStudentGrowthData(studentGrowthDateRange.value[0], studentGrowthDateRange.value[1])
  }
}

// 获取统计数据
const fetchStatementData = async () => {
  try {
    const res = await getStatement()
    if (res.code === 200 && res.data) {
      // 更新统计数据
      statistics.value.studentCount = res.data.studentCount || 0
      statistics.value.teacherCount = res.data.teacherCount || 0
      statistics.value.finishedCourseCount = res.data.finishedLessonsSum || 0
      statistics.value.courseCount = res.data.totalLessonsSum || 0
      statistics.value.instrumentCount = res.data.instrumentCategoryCount || 0
      
      // 更新学员来源分布数据
      const sourceData = res.data.studentSourceCounts || []
      const sourceLabels = []
      const sourceCounts = []
      
      // 将API返回的数据映射到图表数据
      SOURCE_OPTIONS.forEach(option => {
        const found = sourceData.find(item => item.source === option.value)
        sourceLabels.push(option.label)
        sourceCounts.push(found ? found.count : 0)
      })
      
      studentSourceData.value.labels = sourceLabels
      studentSourceData.value.datasets[0].data = sourceCounts
      
      // 更新学员状态分布数据
      const statusData = res.data.studentStatusCounts || []
      const statusLabels = []
      const statusCounts = []
      
      // 将API返回的数据映射到图表数据
      STATUS_OPTIONS.forEach(option => {
        const found = statusData.find(item => item.status === option.value)
        statusLabels.push(option.label)
        statusCounts.push(found ? found.count : 0)
      })
      
      studentStatusData.value.labels = statusLabels
      studentStatusData.value.datasets[0].data = statusCounts
      
      // 更新乐器分布数据
      const instrumentData = res.data.courseInstrumentCategorySums || []
      instrumentDistributionData.value.labels = instrumentData.map(item => item.icName)
      instrumentDistributionData.value.datasets[0].data = instrumentData.map(item => item.sum)
      
      // 设置默认日期范围并获取趋势数据
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 5)
      
      // 设置课程消课趋势的日期范围
      dateRange.value = [
        `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}`,
        `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}`
      ]
      await fetchCourseSalesData(dateRange.value[0], dateRange.value[1])
      
      // 设置学员增长趋势的日期范围
      studentGrowthDateRange.value = [
        `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}`,
        `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}`
      ]
      await fetchStudentGrowthData(studentGrowthDateRange.value[0], studentGrowthDateRange.value[1])
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 如果获取统计数据失败，回退到分别获取各项数据
  }
}

// 获取学员增长趋势数据
const fetchStudentGrowthData = async (startMonth, endMonth) => {
  try {
    // 如果没有提供日期范围，使用默认的近6个月
    if (!startMonth || !endMonth) {
      const now = new Date()
      endMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
      
      const sixMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 5, 1)
      startMonth = `${sixMonthsAgo.getFullYear()}-${String(sixMonthsAgo.getMonth() + 1).padStart(2, '0')}`
    }
    
    // 解析开始和结束日期
    const [startYear, startMonthNum] = startMonth.split('-').map(Number)
    const [endYear, endMonthNum] = endMonth.split('-').map(Number)
    
    // 生成月份列表
    const months = []
    let currentYear = startYear
    let currentMonth = startMonthNum
    
    while (
      currentYear < endYear || 
      (currentYear === endYear && currentMonth <= endMonthNum)
    ) {
      const monthStr = `${currentYear}-${String(currentMonth).padStart(2, '0')}`
      months.push(monthStr)
      
      currentMonth++
      if (currentMonth > 12) {
        currentMonth = 1
        currentYear++
      }
    }
    
    // 调用新的getStudentGrowth接口
    const res = await getStudentGrowth({
      start: startMonth,
      end: endMonth
    })
    
    const monthlyCounts = {}
    months.forEach(month => {
      monthlyCounts[month] = 0
    })
    
    if (res.code === 200 && res.data) {
      res.data.forEach(item => {
        if (monthlyCounts[item.month] !== undefined) {
          monthlyCounts[item.month] = item.count
        }
      })
    }
    
    // 更新图表数据
    studentGrowthTrendData.value.labels = months.map(month => {
      const [year, monthNum] = month.split('-')
      return `${year}年${monthNum}月`
    })
    studentGrowthTrendData.value.datasets[0].data = months.map(month => monthlyCounts[month])
  } catch (error) {
    console.error('获取学员增长数据失败:', error)
  }
}

// 获取课程销售数据
const fetchCourseSalesData = async (startMonth, endMonth) => {
  try {
    // 如果没有提供日期范围，使用默认的近6个月
    if (!startMonth || !endMonth) {
      const now = new Date()
      endMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
      
      const sixMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 5, 1)
      startMonth = `${sixMonthsAgo.getFullYear()}-${String(sixMonthsAgo.getMonth() + 1).padStart(2, '0')}`
    }
    
    // 解析开始和结束日期
    const [startYear, startMonthNum] = startMonth.split('-').map(Number)
    const [endYear, endMonthNum] = endMonth.split('-').map(Number)
    
    // 生成月份列表
    const months = []
    let currentYear = startYear
    let currentMonth = startMonthNum
    
    while (
      currentYear < endYear || 
      (currentYear === endYear && currentMonth <= endMonthNum)
    ) {
      const monthStr = `${currentYear}-${String(currentMonth).padStart(2, '0')}`
      months.push(monthStr)
      
      currentMonth++
      if (currentMonth > 12) {
        currentMonth = 1
        currentYear++
      }
    }
    
    // 调用新的getCourseTrend接口
    const res = await getCourseTrend({
      start: startMonth,
      end: endMonth
    })
    
    const monthlyCounts = {}
    months.forEach(month => {
      monthlyCounts[month] = 0
    })
    
    if (res.code === 200 && res.data) {
      res.data.forEach(item => {
        if (monthlyCounts[item.month] !== undefined) {
          monthlyCounts[item.month] = item.count
        }
      })
    }
    
    // 更新图表数据
    courseSalesTrendData.value.labels = months.map(month => {
      const [year, monthNum] = month.split('-')
      return `${year}年${monthNum}月`
    })
    courseSalesTrendData.value.datasets[0].data = months.map(month => monthlyCounts[month])
  } catch (error) {
    console.error('获取课程销售数据失败:', error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  // 优先使用统一的统计接口
  fetchStatementData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.data-cards {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
  position: relative;
  overflow: hidden;
}

.data-card-content {
  position: relative;
  z-index: 2;
}

.data-card-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.data-card-title {
  font-size: 14px;
  color: #6c757d;
}

.data-card-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 48px;
  opacity: 0.3;
  z-index: 1;
}

.student-icon {
  color: #4e73df;
}

.teacher-icon {
  color: #1cc88a;
}

.course-icon {
  color: #36b9cc;
}

.instrument-icon {
  color: #f6c23e;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.chart-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.chart-container {
  height: 300px;
}

.chart-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-picker-container {
  margin-left: 20px;
}
</style>